var express = require('express');
var router = express.Router();
let { dynamicmodel, livingmodel, fieldmodel, slideShowmodel, activemodel,
    typemodel,
    statusmodel, biaoModel, videoModel, statumodel } = require('../../modules/kk')
const multer = require('multer');
const XLSX = require('xlsx');
const path = require('path');
const multiparty = require('multiparty');
const fs = require('fs-extra');

// // 配置 multer 用于文件上传
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         if (file.fieldname === 'cover') {
//             cb(null, 'uploads/covers');
//         } else if (file.fieldname === 'video') {
//             cb(null, 'uploads/videos');
//         }
//     },
//     filename: function (req, file, cb) {
//         const ext = path.extname(file.originalname);
//         cb(null, Date.now() + ext);
//     }
// });

// const upload = multer({ storage: storage });

const upload = multer({ dest: 'uploads/' });

// 定时任务，例如每分钟检查一次
setInterval(syncActivityStatus, 60 * 1000);

// 原有的接口保持不变
router.post('/addtype', (req, res) => {
    typemodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addstatu', (req, res) => {
    statumodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addstatus', (req, res) => {
    statusmodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addactive', (req, res) => {
    activemodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addbiao', (req, res) => {
    biaoModel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addynamic', (req, res) => {
    dynamicmodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addfield', (req, res) => {
    fieldmodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/addliving', (req, res) => {
    livingmodel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.get('/gettype', async (req, res) => {
    let list = await typemodel.find()
    res.send({
        code: 200,
        list
    })
})
router.get('/getstatus', async (req, res) => {
    let list = await statusmodel.find()
    res.send({
        code: 200,
        list
    })
})
router.get('/getactive', async (req, res) => {
    let { name, page, pagesize, startdate, endate, tid, sid } = req.query
    console.log(tid);

    let obj = [{}]
    let na = new RegExp(name)
    if (name) {
        obj.push({ content: na })
    }
    if (startdate) {
        obj.push({ start_time: { $gte: startdate } })
    }
    if (endate) {
        obj.push({ start_time: { $lte: endate } })
    }
    if (tid != undefined) {
        obj.push({ tid })
    }
    if (sid != undefined) {
        obj.push({ sid })
    }
    let list = await activemodel.find({ $and: obj }).populate(['sid', 'tid']).skip((page - 1) * pagesize).limit(pagesize)
    let total = await activemodel.find({ $and: obj }).countDocuments()
    res.send({
        code: 200,
        list,
        total
    })
})

router.get('/getliving', async (req, res) => {
    let { name, page, pagesize, startdate, endate } = req.query
    let result = await livingmodel.aggregate([
        {
            $group: {
                _id: '$nid',
                count: { $sum: 1 }
            }
        },
    ]);
    console.log(result);

    let obj = [{}]
    let na = new RegExp(name)
    if (name) {
        obj.push({ content: na })
    }
    if (startdate) {
        obj.push({ start_time: { $gte: startdate } })
    }
    if (endate) {
        obj.push({ start_time: { $lte: endate } })
    }
    let list = await livingmodel.find({ $and: obj }).skip((page - 1) * pagesize).limit(pagesize)
    let total = await livingmodel.find({ $and: obj }).countDocuments()
    res.send({
        code: 200,
        list,
        total
    })
})
router.get('/getslide', async (req, res) => {
    let { page, pagesize } = req.query
    let list = await slideShowmodel.find().skip((page - 1) * pagesize).limit(pagesize)
    let total = await slideShowmodel.find().countDocuments()
    res.send({
        code: 200,
        list,
        total
    })
})
router.get('/getfield', async (req, res) => {
    let { page, pagesize } = req.query
    let list = await fieldmodel.find().skip((page - 1) * pagesize).limit(pagesize)
    let total = await fieldmodel.find().countDocuments()
    res.send({
        code: 200,
        list,
        total
    })
})
router.get('/topicnum', async (req, res) => {
    let { nid } = req.query
    const num = await livingmodel.countDocuments({ nid });
    res.send({
        code: 200,
        num
    })
})
router.get('/getdynamic', async (req, res) => {
    let { name, page, pagesize, startdate, endate } = req.query
    console.log(startdate, endate);

    let obj = [{}]
    let na = new RegExp(name)
    if (name) {
        obj.push({ name: na })
    }
    if (startdate) {
        obj.push({ start_time: { $gte: startdate } })
    }
    if (endate) {
        obj.push({ start_time: { $lte: endate } })
    }

    let list = await dynamicmodel.find({ $and: obj }).skip((page - 1) * pagesize).limit(pagesize)
    let total = await dynamicmodel.find({ $and: obj }).countDocuments()

    res.send({
        code: 200,
        list,
        total
    })
})
router.get('/deldynamic', async (req, res) => {
    await dynamicmodel.deleteOne({ _id: req.query.id })
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.post('/upload', upload.single('excelFile'), async (req, res) => {
    try {
        const workbook = XLSX.readFile(req.file.path);
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const data = XLSX.utils.sheet_to_json(worksheet);
        console.log(data);
        await fieldmodel.create(
            data.map(item => {
                return item
            })
        )

        res.status(200).send('文件处理成功');
    } catch (err) {
        console.error(err);
        res.status(500).send('文件处理失败');
    }
});
router.get('/delfield', async (req, res) => {
    await fieldmodel.deleteOne({ _id: req.query._id })
    res.send({
        code: 200,
        msg: 'success'
    })
})


router.post('/uploads', (req, res) => {
    let form = new multiparty.Form();
    form.uploadDir = 'upload';
    form.parse(req, (err, fields, files) => {
        if (err) {
            console.error('文件上传出错', err);
            return res.status(500).send({
                code: 500,
                msg: '文件上传失败'
            });
        }
        if (!files.file || files.file.length === 0) {
            return res.status(400).send({
                code: 400,
                msg: '未上传文件'
            });
        }

        const file = files.file[0];
        const ext = path.extname(file.originalFilename);
        const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif'];
        if (!allowedExtensions.includes(ext)) {
            fs.unlinkSync(file.path);
            return res.status(400).send({
                code: 400,
                msg: '不支持的文件类型'
            });
        }

        res.send({
            path: `http://localhost:3000/${file.path}`
        });
    });
});

// 添加轮播图数据接口
router.post('/addslideShow', async (req, res) => {
    try {
        await slideShowmodel.create(req.body);
        res.send({
            code: 200,
            msg: 'success'
        });
    } catch (error) {
        console.error('保存数据出错', error);
        res.status(500).send({
            code: 500,
            msg: '保存数据失败'
        });
    }
});
router.get('/delslide', async (req, res) => {
    await slideShowmodel.deleteOne({ _id: req.query._id })
    res.send({
        code: 200,
        msg: 'success'
    })
})
router.get('/getbiao', async (req, res) => {
    let list = await biaoModel.find()
    res.send({
        code: 200,
        list
    })
})
router.get('/getstatu', async (req, res) => {
    res.send({
        code: 200,
        list: await statumodel.find()
    })
})

// 添加视频信息
router.post('/addvideo', express.json(), async (req, res) => {
    const { name, title, status, img, video, tagIds, publishDate } = req.body;
      const finalPublishDate = publishDate instanceof Date ? publishDate : new Date(publishDate);
    // console.log(req.body);
    videoModel.create(req.body)
    res.send({
        code: 200,
        msg: 'success'
    })
    
    // try {
    //     await videoModel.create({
    //         name,
    //         title,
    //         status,
    //         img,
    //         video,
    //         tagIds,
    //         publishDate
    //     });
    //     res.sendStatus(200);
    // } catch (error) {
    //     console.error('保存视频信息失败', error);
    //     res.status(500).send('保存视频信息失败');
    // }
});

async function syncActivityStatus() {
    try {
        // 获取当前时间
        const now = new Date();

        // 从数据库中查找状态为 '已发布' 的状态文档
        const publishedStatus = await statumodel.findOne({ lable: '已发布' });
        // 从数据库中查找状态为 '待发布' 的状态文档
        const pendingStatus = await statumodel.findOne({ lable: '待发布' });

        // 更新活动状态
        // 条件：发布时间小于当前时间且当前状态为 '待发布'
        await videoModel.updateMany(
            { publishTime: { $lt: now }, zid: pendingStatus._id },
            { zid: publishedStatus._id }
        );

        console.log('活动状态同步完成');
    } catch (error) {
        console.error('同步活动状态时出错:', error);
    }
}

router.get('/getvideo', async (req, res) => {
    let { name, page, pagesize, zid } = req.query
    console.log(zid);
    
    let obj = [{}]
    if (zid) {
        obj.push({ zid


            
         })
    }
     let list = await videoModel.find({ $and: obj }).populate(['zid', 'bid']).skip((page - 1) * pagesize).limit(pagesize)
    let total = await videoModel.find({ $and: obj }).countDocuments()
    res.send({
        code: 200,
        list,
        total
    })
})
// 批量删除话题
router.delete('/deleteTopics', async (req, res) => {
    const { ids } = req.body;
    try {
        await livingmodel.deleteMany({ _id: { $in: ids } });
        res.status(200).json({ message: '批量删除成功' });
    } catch (error) {
        res.status(500).json({ error: '批量删除失败' });
    }
});
module.exports = router;